package cn.usian.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.usian.common.ResultEnum;
import cn.usian.common.Results;
import cn.usian.exception.LesseeException;
import cn.usian.pojo.User;
import cn.usian.threadlocal.AuthThreadLocal;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LessInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String requestURI = request.getRequestURI();
        if (!requestURI.contains("auth")){
            String token = request.getHeader("token");
            if (!StrUtil.isBlankIfStr(token)){
                String userRedis = redisTemplate.boundValueOps(token).get();
                AuthThreadLocal.set(JSON.parseObject(userRedis, User.class));
                return true;
            }
            throw new LesseeException(ResultEnum.LOGIN_OUT);
        }


        return true;
    }
}
